package com.example.myapplication14_5;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.MediaController;
import android.widget.Toast;
import android.widget.VideoView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements VideoAdapter.OnVideoClickListener {

    // 核心组件引用
    private VideoView videoView;
    private Button btnPlay, btnStop;
    private RecyclerView videoListRecyclerView;

    // 控制器与视频路径
    private MediaController mediaController;
    private Uri videoUri;

    // 视频列表相关
    private VideoAdapter videoAdapter;
    private List<VideoItem> videoList;
    private int currentVideoIndex = -1;

    private static final int PERMISSION_REQUEST_CODE = 123;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 初始化界面控件
        initViews();

        // 配置视频播放器
        setupVideoView();

        // 设置按钮点击事件
        setupButtonListeners();

        // 检查权限并扫描视频文件
        checkPermissionAndScanVideos();
    }

    private void checkPermissionAndScanVideos() {
        if (checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
                    PERMISSION_REQUEST_CODE);
        } else {
            scanVideoFiles();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                scanVideoFiles();
            } else {
                Toast.makeText(this, "需要存储权限来访问视频文件", Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * 初始化所有 UI 组件
     */
    private void initViews() {
        videoView = findViewById(R.id.videoView);
        btnPlay = findViewById(R.id.btnPlay);
        btnStop = findViewById(R.id.btnStop);
        videoListRecyclerView = findViewById(R.id.videoListRecyclerView);

        // 初始化RecyclerView
        videoListRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        videoList = new ArrayList<>();
        videoAdapter = new VideoAdapter(this);
        videoListRecyclerView.setAdapter(videoAdapter);
    }

    /**
     * 扫描SD卡中的视频文件
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    private void scanVideoFiles() {
        String path = Environment.getExternalStorageDirectory().getPath();
        videoList.clear();
        scanDirectory(new File(path));

        // 按文件名排序
        videoList.sort((v1, v2) -> v1.getTitle().compareToIgnoreCase(v2.getTitle()));
        videoAdapter.updateVideoList(videoList);

        if (!videoList.isEmpty()) {
            currentVideoIndex = 0;
            playVideo(videoList.get(0));
        } else {
            Toast.makeText(this, "未找到视频文件", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 递归扫描目录中的视频文件
     */
    private void scanDirectory(File directory) {
        File[] files = directory.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    scanDirectory(file);
                } else {
                    String name = file.getName().toLowerCase();
                    if (name.endsWith(".mp4") || name.endsWith(".3gp") ||
                            name.endsWith(".mkv") || name.endsWith(".avi")) {
                        String duration = getVideoDuration(file.getAbsolutePath());
                        videoList.add(new VideoItem(file.getName(), file.getAbsolutePath(),
                                file.length(), duration));
                    }
                }
            }
        }
    }

    private String getVideoDuration(String videoPath) {
        android.media.MediaMetadataRetriever retriever = new android.media.MediaMetadataRetriever();
        try {
            retriever.setDataSource(videoPath);
            String time = retriever.extractMetadata(android.media.MediaMetadataRetriever.METADATA_KEY_DURATION);
            long timeInMillis = Long.parseLong(time);
            long minutes = (timeInMillis / 1000) / 60;
            long seconds = (timeInMillis / 1000) % 60;
            return String.format("%d:%02d", minutes, seconds);
        } catch (Exception e) {
            return "未知";
        } finally {
            try {
                retriever.release();
            } catch (Exception e) {
                // 忽略释放时的异常
            }
        }
    }

    /**
     * 配置 VideoView 的播放设置
     */
    private void setupVideoView() {
        // 设置 MediaController
        mediaController = new MediaController(this);
        mediaController.setAnchorView(videoView);
        videoView.setMediaController(mediaController);

        // 视频准备监听器
        videoView.setOnPreparedListener(mp -> {
            mp.setVideoScalingMode(MediaPlayer.VIDEO_SCALING_MODE_SCALE_TO_FIT);
        });

        // 设置播放完成监听器，自动播放下一个视频
        videoView.setOnCompletionListener(mp -> playNextVideo());

        // 设置错误监听
        videoView.setOnErrorListener((mp, what, extra) -> {
            Toast.makeText(MainActivity.this, "视频播放出错", Toast.LENGTH_SHORT).show();
            return true;
        });
    }

    /**
     * 播放指定的视频
     */
    private void playVideo(VideoItem video) {
        if (video != null) {
            videoUri = Uri.parse(video.getPath());
            videoView.setVideoURI(videoUri);
            videoView.start();
            btnPlay.setText("暂停");
        }
    }

    /**
     * 播放下一个视频
     */
    private void playNextVideo() {
        if (videoList != null && !videoList.isEmpty()) {
            currentVideoIndex = (currentVideoIndex + 1) % videoList.size();
            playVideo(videoList.get(currentVideoIndex));
        }
    }

    /**
     * 播放上一个视频
     */
    private void playPreviousVideo() {
        if (videoList != null && !videoList.isEmpty()) {
            currentVideoIndex = (currentVideoIndex - 1 + videoList.size()) % videoList.size();
            playVideo(videoList.get(currentVideoIndex));
        }
    }

    @Override
    public void onVideoClick(VideoItem video, int position) {
        currentVideoIndex = position;
        playVideo(video);
    }

    /**
     * 设置播放 / 停止按钮的点击事件
     */
    private void setupButtonListeners() {
        btnPlay.setOnClickListener(v -> togglePlayPause());
        btnStop.setOnClickListener(v -> stopAndResetVideo());

        Button btnPrevious = findViewById(R.id.btnPrevious);
        Button btnNext = findViewById(R.id.btnNext);

        btnPrevious.setOnClickListener(v -> {
            if (currentVideoIndex > 0) {
                currentVideoIndex--;
                playVideo(videoList.get(currentVideoIndex));
            } else {
                Toast.makeText(this, "已经是第一个视频", Toast.LENGTH_SHORT).show();
            }
        });

        btnNext.setOnClickListener(v -> {
            if (currentVideoIndex < videoList.size() - 1) {
                currentVideoIndex++;
                playVideo(videoList.get(currentVideoIndex));
            } else {
                Toast.makeText(this, "已经是最后一个视频", Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 切换播放和暂停状态，并更新按钮文本
     */
    private void togglePlayPause() {
        if (videoView.isPlaying()) {
            videoView.pause();
            btnPlay.setText("播放");
        } else {
            videoView.start();
            btnPlay.setText("暂停");
        }
    }

    /**
     * 停止并重置视频播放
     */
    private void stopAndResetVideo() {
        videoView.stopPlayback();
        if (currentVideoIndex >= 0 && currentVideoIndex < videoList.size()) {
            playVideo(videoList.get(currentVideoIndex));
            videoView.pause();
            btnPlay.setText("播放");
        }
    }

    /**
     * 当 Activity 暂停时暂停视频播放
     */
    @Override
    protected void onPause() {
        super.onPause();
        if (videoView != null && videoView.isPlaying()) {
            videoView.pause();
            btnPlay.setText("播放");
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (videoList.isEmpty()) {
            scanVideoFiles();
        }
    }

    /**
     * 清理资源，防止内存泄漏
     */
    @Override
    protected void onDestroy() {
        if (videoView != null) {
            videoView.stopPlayback();
            videoView.suspend(); // 释放 MediaPlayer 资源
            videoView = null; // 防止内存泄漏
        }
        if (mediaController != null) {
            mediaController = null;
        }
        videoList.clear();
        super.onDestroy();
    }
}